import java.util.Random;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.Execution;
import org.apache.log4j.Logger;

public class SignalSender {
	private static Logger logger = Logger.getLogger("SignalSender");

	public static void main(String[] args) {
		sendSignal("738958", "catchSignal");
	}

	public static void sendSignal(String processInstanceId, String signalEventSubscriptionName) {
	//	logger.info(processInstanceId + " " + signalEventSubscriptionName);
		sendSignalThread(processInstanceId, signalEventSubscriptionName);
	}

	private static void sendSignalThread(final String processInstanceId, final String signalEventSubscriptionName) {
		Thread one = new Thread() {
			public void run() {
				try {
					for (int i = 0; i < 10; i++) {
						synchronized (Lock.getLock(processInstanceId)) {						
							ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
							RuntimeService runtimeService = processEngine.getRuntimeService();
							if (runtimeService != null) {
								Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId)
										.signalEventSubscriptionName(signalEventSubscriptionName).singleResult();
								if (execution != null) {
									runtimeService.signal(execution.getId());
									logger.info("signal sended "+processInstanceId);
									Lock.deleteLock(processInstanceId);
									break;
								}
							}
							logger.warn("signal not sended for "+processInstanceId);
							Lock.deleteLock(processInstanceId);
						}
						Thread.sleep(new Random().nextInt(5000));
					}
				} catch (Exception e) {
					logger.info(e);
				}
			}
		};
		one.start();
	}
}
